package org.jfrog.jade.plugins.common.util;

/*
 * Copyright 2005-2006 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.InputStream;
import java.net.URL;

/**
 * Wrapping the class loader access issues and need to play with factory parameter
 * @author Fred Simon
 */
public class Loader {

    public static Class loadClass(String className) throws ClassNotFoundException {
        return loadClass(className, Loader.class);
    }

    public static Class loadClass(String className, Class currentClass) throws ClassNotFoundException {
        ClassLoader contextClassLoader = getClassLoader(currentClass);
        Class aClass = contextClassLoader.loadClass(className);
        return aClass;
    }

    public static URL getResource(String resourceName) {
        return getResource(resourceName, Loader.class);
    }

    public static URL getResource(String resourceName, Class currentClass) {
        return getClassLoader(currentClass).getResource(resourceName);
    }

    public static InputStream getResourceAsStream(String resourceName) {
        return getResourceAsStream(resourceName, Loader.class);
    }

    public static InputStream getResourceAsStream(String resourceName, Class currentClass) {
        InputStream is = getClassLoader(currentClass).getResourceAsStream(resourceName);
        if (is == null)
            is = currentClass.getResourceAsStream(resourceName);
        return is;
    }

    public static ClassLoader getClassLoader(Class currentClass) {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        if (contextClassLoader == null) {
            contextClassLoader = currentClass.getClassLoader();
        }
        return contextClassLoader;
    }
}
